package com.ddn.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * ❀❀❀---扎根---❀❀❀
 *     ❤ @libing ❤
 */

@WebFilter({"*.html"})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    /**
     * 过滤器,防止SQL注入
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //获取请求路径，登录要放行
        String requestURI = req.getRequestURI();
        System.out.println("requestURI====>"+requestURI);

        if (requestURI.contains("login1")){
            chain.doFilter(request,response);
            //既然放行，后面就别执行
            return;
        }else if (requestURI.contains("login")){
            chain.doFilter(request,response);
            //既然放行，后面就别执行
            return;
        }

        //获取session
        HttpSession session = req.getSession();
        Object user = session.getAttribute("username");
        if (user != null){//有值，登陆成功
            chain.doFilter(request,response);
            //既然放行，后面的不用执行
            return;
        }else {
            System.out.println("没登陆，请登录");
            resp.sendRedirect("/login1.html");
        }
    }

    @Override
    public void destroy() {}
}
